package com.tdam2014.grupo3.flickr.interfaces;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.tdam2014.grupo3.entities.Comment;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.Parameter;
import com.tdam2014.grupo3.flickr.Response;
import com.tdam2014.grupo3.flickr.Transport;

/**
 * Interface for working with Flickr Comments.
 *
 * @author Till Krech, adapted by Lucas Cunibertti for Flickr Viewer.
 */
public class CommentInterface {
	
    public static final String METHOD_GET_LIST       = "flickr.photos.comments.getList";

    private String apiKey;
    private Transport transportAPI;

    public CommentInterface(
        String apiKey,
        Transport transport
    ) {
        this.apiKey = apiKey;
        this.transportAPI = transport;
    }

    /**
     * Returns the comments for a photo.
     * This method does not require authentication.
     *
     * @param photoId The id of the photo to fetch comments for.
     * @return a List of Comment objects.
     * @throws FlickrException
     * @throws IOException
     * @throws JSONException
     */
    public ArrayList<Comment> getList(String photoId)
      throws FlickrException, IOException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_GET_LIST));
        parameters.add(new Parameter("api_key", apiKey));
        parameters.add(new Parameter("photo_id", photoId));

        Response response = transportAPI.get(transportAPI.getPath(), parameters);
        
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        
        JSONObject commentsObject = response.getData().getJSONObject("comments");
        JSONArray commentArray = commentsObject.optJSONArray("comment");
        ArrayList<Comment> comments = new ArrayList<Comment>();
        
        for (int i = 0; commentArray != null && i < commentArray.length(); i++) {
            JSONObject commentElement = commentArray.getJSONObject(i);
            comments.add(new Comment(commentElement));
        }
        
        return comments;
    }
}